package com.ivc.report.action;

import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;

import com.cs.framework.common.util.CommonUtils;
import com.cs.framework.ui.bo.UIData;
import com.cs.framework.ui.web.UI;
import com.cs.framework.web.annotation.Mapping;
import com.cs.framework.web.handler.Web;
import com.ivc.report.service.ReportService;

/**
 * 报表抽象Action类
 *
 * @author hedongzhou
 *
 */
@SuppressWarnings("all")
public abstract class AbstractReportAction {

	/**
	 * 获取页面ID
	 * 
	 * @return
	 */
	public abstract String getPageId();

	/**
	 * 获取报表Service名称
	 * 
	 * @return
	 */
	public abstract String getServiceName();

	/**
	 * 导出报表文件名
	 * 
	 * @return
	 */
	public abstract String getFileName();

	/**
	 * 进入报表页面
	 */
	@Mapping
	public void mainPage() {
		UI.returnPage(getPageId());
	}

	/**
	 * 查询
	 * 
	 * @return
	 */
	@Mapping
	public Object query() {
		ReportService service = Web.getHandlerContext().getBean(getServiceName(), ReportService.class);

		Map params = Web.bind(HashMap.class);

		List<Map> list = service.query(params);
		int count = service.count(params);

		return new UIData(list, count);
	}

	/**
	 * 导出Excel
	 * 
	 */
	@Mapping
	public void export() {
		ReportService service = Web.getHandlerContext().getBean(getServiceName(), ReportService.class);

		Map params = Web.bind(HashMap.class);

		try {
			Workbook book = service.createExcel(params);

			HttpServletResponse response = Web.getResponse();
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-disposition", "attachment;filename="
					+ new String(getFileName().getBytes(), "ISO8859-1") + ".xls");

			OutputStream ouputStream = null;
			try {
				ouputStream = response.getOutputStream();
				book.write(ouputStream);
				ouputStream.flush();
			} finally {
				if (ouputStream != null) {
					ouputStream.close();
				}
			}
		} catch (Exception e) {
			CommonUtils.throwRun(e);
		}
	}

}
